// toastr.info('注册成功')
// toastr.success('注册成功')
// toastr.warning('注册成功')
// toastr.error('注册成功')

const a1 = document.querySelector('.register a')
const a2 = document.querySelector('.login a')
const login = document.querySelector('.login')
const register = document.querySelector('.register')

a2.onclick = function(){
  login.style.display = 'none'
  register.style.display = 'block'
}

a1.onclick = function(){
  login.style.display = 'block'
  register.style.display = 'none'
}

let  input1 = document.querySelector('.register [name=username]')
let  input2 = document.querySelector('.register [name=password]')
let  input3 = document.querySelector('.login [name=username]')
let  input4 = document.querySelector('.login [name=password]')

function verifyInput(ele,txt1,reg,txt2){
  ele.onkeyup = function(){
    if(this.value === ''){
      this.nextElementSibling.style.display = 'block'
      this.nextElementSibling.innerHTML = txt1
      return
    }else{
      this.nextElementSibling.style.display = 'none'
      this.nextElementSibling.innerHTML = ''
    }
    if(reg.test(this.value)){
      this.nextElementSibling.style.display = 'none'
      this.nextElementSibling.innerHTML = ''
    }else{
      this.nextElementSibling.style.display = 'block'
      this.nextElementSibling.innerHTML = txt2
    }
  }
}
verifyInput(input1,'用户名不能为空',/^\S{2,15}$/,'用户名必须在2-15位之间')
verifyInput(input2,'密码不能为空',/^\S{6,15}$/,'密码必须在6-15位之间')
verifyInput(input3,'用户名不能为空',/^\S{2,15}$/,'用户名必须在2-15位之间')
verifyInput(input4,'密码不能为空',/^\S{6,15}$/,'密码必须在6-15位之间')

// 注册功能
let form1 = document.querySelector('.register form')
form1.addEventListener('submit',function(e){
  e.preventDefault()
  axios({
    url:'/api/register',
    method:'post',
    data: { 
      username : input1.value,
      password : input2.value
    },
  }).then(({data:res})=>{
    //成功回调
    // console.log(res)
  //   if(res.code == 1){
  //     return toastr.warning(res.message)
  //   }
    if(res.code == 0){
      // 成功提示
      toastr.success('注册成功')
      // 清空表单
      form1.reset()
      // 跳转模块
      a1.click()
    }
  });
})

// 登录功能
let form2 = document.querySelector('.login form')
form2.addEventListener('submit',function(e){
  e.preventDefault()
  axios({
    url:'/api/login',
    method:'POST',
    data: { 
      username : input3.value ,
      password : input4.value
    },
  }).then(({data:res})=>{
    //成功回调
    // console.log(res)
  //   if(res.code == 1){
  //     return toastr.warning(res.message)
  //   }
    if(res.code == 0){
      // 登入成功提示
      toastr.success('登入成功')
      // 跳转页面
      location.href = './index.html'
      // 保存token 
      localStorage.setItem('token',res.token)
    }
  });
})